package com.rainy.mod.plugin.common.util;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

public class JsonUtils {
	
	protected static Logger logger = Logger.getLogger(JsonUtils.class);
	
	private static ObjectMapper getMapper() {
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.configure(Feature.USE_GETTERS_AS_SETTERS, false);
		
		return mapper;
	}
	
	public static String toJson(Object obj) {
		ObjectMapper mapper = getMapper();
		String json = "";
		try {
			json = mapper.writeValueAsString(obj);
		} catch (Exception e) {
			logger.error("toJson error: ", e);
		}
		
		return json;
	}
	
	public static <T> T toBean(String content, Class<T> clazz) {
		ObjectMapper mapper = getMapper();
		
		try {
			return mapper.readValue(content, clazz);
		} catch (Exception e) {
			logger.error("toBean error: ", e);
		}
		
		return null;
	}
	
	public static <T> List<T> toList(String content, TypeReference<? extends List<T>> tr) {
		ObjectMapper mapper = getMapper();
		try {
			return mapper.readValue(content, tr);
		} catch (Exception e) {
			logger.error("toList error: ", e);
		}
		
		return null;
	}
	
	public static <T> Set<T> toSet(String content, TypeReference<? extends Set<T>> tr) {
		ObjectMapper mapper = getMapper();
		try {
			return mapper.readValue(content, tr);
		} catch (Exception e) {
			logger.error("toSet error: ", e);
		}
		
		return null;
	}
	
	public static <K, V> Map<K, V> toMap(String content, TypeReference<? extends Map<K, V>> tr) {
		ObjectMapper mapper = getMapper();
		try {
			return mapper.readValue(content, tr);
		} catch (Exception e) {
			logger.error("toMap error: ", e);
		}
		
		return null;
	}
	
	public static void main(String[] args) {
		Date d = new Date();
		
		String json1 = toJson(d);
		System.out.println("u==" + json1);
	}
	

}
